import { createContext, useContext, useState } from 'react';
import { useImmer } from './immer';

const FlowContext = createContext();

export function FlowDataProvider({ children }) {
  const [data, update] = useImmer({
    flowKey: '',
    flowName: '',
    flowType: '',
    flowContent: [],
    flowInputParams: [],
    flowOutputParams: [],
    flowVariables: [],
    id: null,
    remark: '',
  });

  function getFlowNodes() {
    return data.flowContent;
  }

  function getFlowNode(key) {
    return data.flowContent.find(node => node.key === key);
  }

  function updateFlowNode(key, newData) {
    update(draft => {
      const node = draft.flowContent.find(node => node.key === key);
      if (node) {
        Object.assign(node, newData);
      }
    });
  }

  const flowContext = {
    data,
    update,
    getFlowNodes,
    getFlowNode,
    updateFlowNode,
  };

  return (
    <FlowContext.Provider value={flowContext}>
      {children}
    </FlowContext.Provider>
  );
}

export function useFlowData() {
  const context = useContext(FlowContext);
  if (!context) {
    throw new Error('useFlowData must be used within a FlowDataProvider');
  }
  return context;
} 